<?php

class Admin extends MY_Controller_admin {

    public function __construct() {
        parent::__construct();
        $this->load->model('admin/page_model');
        // $this->load->model('main/menu_model');
    }

    public function index($page = 'index') {
        if (!$this->ion_auth->logged_in()) {
            $this->_validate();
        }

        $page = "admin/" . $page;

        if (!file_exists('application/views/' . $page . '.php')) {
            // Whoops, we don't have a page for that!
            show_404();
        }

        $data['title'] = 'Админка'; // Capitalize the first letter



        $this->_render($page, $data);
    }

    public function login() {
        $this->data['title'] = "Login";

        //validate form input
        $this->form_validation->set_rules('identity', 'Identity', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');

        if ($this->form_validation->run() == true) {
            //check to see if the user is logging in
            //check for "remember me"
            $remember = (bool) $this->input->post('remember');

            if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember)) {
                //if the login is successful
                //redirect them back to the home page
                $this->session->set_flashdata('message', $this->ion_auth->messages());
                redirect('/admin/admin', 'refresh');
            } else {
                //if the login was un-successful
                //redirect them back to the login page
                $this->session->set_flashdata('message', $this->ion_auth->errors());
                redirect('admin/admin/login', 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
            }
        } else {
            //the user is not logging in so display the login page
            //set the flash data error message if there is one
            $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

            $this->data['identity'] = array('name' => 'identity',
                'id' => 'identity',
                'type' => 'text',
                'value' => $this->form_validation->set_value('identity'),
            );
            $this->data['password'] = array('name' => 'password',
                'id' => 'password',
                'type' => 'password',
            );

            $this->_render('admin/auth/login', $this->data);
        }
    }

    public function users() {
        if (!$this->ion_auth->logged_in()) {
            redirect('admin/admin/login', 'refresh');
        }

        $this->data['title'] = "Пользователи";
        //set the flash data error message if there is one
        $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

        //list the users
        $this->data['users'] = $this->ion_auth->users()->result();
        foreach ($this->data['users'] as $k => $user) {
            $this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
        }

        $this->_render('admin/auth/index', $this->data);
    }

    public function logout() {
        $this->data['title'] = "Logout";

        //log the user out
        $logout = $this->ion_auth->logout();

        //redirect them to the login page
        $this->session->set_flashdata('message', $this->ion_auth->messages());
        redirect('admin/admin/login', 'refresh');
    }

    //create a new user
    public function create_user() {
        $this->data['title'] = "Create User";

        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }

        //validate form input
        $this->form_validation->set_rules('first_name', $this->lang->line('create_user_validation_fname_label'), 'required|xss_clean');
        $this->form_validation->set_rules('last_name', $this->lang->line('create_user_validation_lname_label'), 'required|xss_clean');
        $this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email');
        $this->form_validation->set_rules('phone', $this->lang->line('create_user_validation_phone_label'), 'required|xss_clean');
        $this->form_validation->set_rules('company', $this->lang->line('create_user_validation_company_label'), 'required|xss_clean');
        $this->form_validation->set_rules('password', $this->lang->line('create_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
        $this->form_validation->set_rules('password_confirm', $this->lang->line('create_user_validation_password_confirm_label'), 'required');

        if ($this->form_validation->run() == true) {
            $username = strtolower($this->input->post('first_name')) . ' ' . strtolower($this->input->post('last_name'));
            $email = $this->input->post('email');
            $password = $this->input->post('password');

            $additional_data = array(
                'first_name' => $this->input->post('first_name'),
                'last_name' => $this->input->post('last_name'),
                'company' => $this->input->post('company'),
                'phone' => $this->input->post('phone'),
            );
        }
        if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email, $additional_data)) {
            //check to see if we are creating the user
            //redirect them back to the admin page
            $this->session->set_flashdata('message', $this->ion_auth->messages());
            redirect("admin/admin/users", 'refresh');
        } else {
            //display the create user form
            //set the flash data error message if there is one
            $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

            $this->data['first_name'] = array(
                'name' => 'first_name',
                'id' => 'first_name',
                'type' => 'text',
                'value' => $this->form_validation->set_value('first_name'),
            );
            $this->data['last_name'] = array(
                'name' => 'last_name',
                'id' => 'last_name',
                'type' => 'text',
                'value' => $this->form_validation->set_value('last_name'),
            );
            $this->data['email'] = array(
                'name' => 'email',
                'id' => 'email',
                'type' => 'text',
                'value' => $this->form_validation->set_value('email'),
            );
            $this->data['company'] = array(
                'name' => 'company',
                'id' => 'company',
                'type' => 'text',
                'value' => $this->form_validation->set_value('company'),
            );
            $this->data['phone'] = array(
                'name' => 'phone',
                'id' => 'phone',
                'type' => 'text',
                'value' => $this->form_validation->set_value('phone'),
            );
            $this->data['password'] = array(
                'name' => 'password',
                'id' => 'password',
                'type' => 'password',
                'value' => $this->form_validation->set_value('password'),
            );
            $this->data['password_confirm'] = array(
                'name' => 'password_confirm',
                'id' => 'password_confirm',
                'type' => 'password',
                'value' => $this->form_validation->set_value('password_confirm'),
            );

            $this->_render('admin/auth/create_user', $this->data);
        }
    }

    public function create_group() {
        $this->data['title'] = $this->lang->line('create_group_title');

        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }

        //validate form input
        $this->form_validation->set_rules('group_name', $this->lang->line('create_group_validation_name_label'), 'required|alpha_dash|xss_clean');
        $this->form_validation->set_rules('description', $this->lang->line('create_group_validation_desc_label'), 'xss_clean');

        if ($this->form_validation->run() == TRUE) {
            $new_group_id = $this->ion_auth->create_group($this->input->post('group_name'), $this->input->post('description'));
            if ($new_group_id) {
                // check to see if we are creating the group
                // redirect them back to the admin page
                $this->session->set_flashdata('message', $this->ion_auth->messages());
                redirect("admin/admin/users", 'refresh');
            }
        } else {
            //display the create group form
            //set the flash data error message if there is one
            $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

            $this->data['group_name'] = array(
                'name' => 'group_name',
                'id' => 'group_name',
                'type' => 'text',
                'value' => $this->form_validation->set_value('group_name'),
            );
            $this->data['description'] = array(
                'name' => 'description',
                'id' => 'description',
                'type' => 'text',
                'value' => $this->form_validation->set_value('description'),
            );

            $this->_render('admin/auth/create_group', $this->data);
        }
    }

    //edit a group
    function edit_group($id) {
        // bail if no group id given
        if (!$id || empty($id)) {
            redirect('admin/admin/users', 'refresh');
        }

        $this->data['title'] = $this->lang->line('edit_group_title');

        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }

        $group = $this->ion_auth->group($id)->row();

        //validate form input
        $this->form_validation->set_rules('group_name', $this->lang->line('edit_group_validation_name_label'), 'required|alpha_dash|xss_clean');
        $this->form_validation->set_rules('group_description', $this->lang->line('edit_group_validation_desc_label'), 'xss_clean');

        if (isset($_POST) && !empty($_POST)) {
            if ($this->form_validation->run() === TRUE) {
                $group_update = $this->ion_auth->update_group($id, $_POST['group_name'], $_POST['group_description']);

                if ($group_update) {
                    $this->session->set_flashdata('message', $this->lang->line('edit_group_saved'));
                } else {
                    $this->session->set_flashdata('message', $this->ion_auth->errors());
                }
                redirect("admin/admin/users", 'refresh');
            }
        }

        //set the flash data error message if there is one
        $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

        //pass the user to the view
        $this->data['group'] = $group;

        $this->data['group_name'] = array(
            'name' => 'group_name',
            'id' => 'group_name',
            'type' => 'text',
            'value' => $this->form_validation->set_value('group_name', $group->name),
        );
        $this->data['group_description'] = array(
            'name' => 'group_description',
            'id' => 'group_description',
            'type' => 'text',
            'value' => $this->form_validation->set_value('group_description', $group->description),
        );

        $this->_render('admin/auth/edit_group', $this->data);
    }

    //activate the user
    function activate($id, $code = false) {
        if ($code !== false) {
            $activation = $this->ion_auth->activate($id, $code);
        } else if ($this->ion_auth->is_admin()) {
            $activation = $this->ion_auth->activate($id);
        }

        if ($activation) {
            //redirect them to the auth page
            $this->session->set_flashdata('message', $this->ion_auth->messages());
            redirect("admin/admin/users", 'refresh');
        } else {
            //redirect them to the forgot password page
            $this->session->set_flashdata('message', $this->ion_auth->errors());
            redirect("auth/forgot_password", 'refresh');
        }
    }

    //deactivate the user
    function deactivate($id = NULL) {
        
        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }
        
        $id = $this->config->item('use_mongodb', 'ion_auth') ? (string) $id : (int) $id;

        $this->load->library('form_validation');
        $this->form_validation->set_rules('confirm', $this->lang->line('deactivate_validation_confirm_label'), 'required');
        $this->form_validation->set_rules('id', $this->lang->line('deactivate_validation_user_id_label'), 'required|alpha_numeric');

        if ($this->form_validation->run() == FALSE) {
            // insert csrf check
            $this->data['csrf'] = $this->_get_csrf_nonce();
            $this->data['user'] = $this->ion_auth->user($id)->row();

            $this->_render('admin/auth/deactivate_user', $this->data);
        } else {
            // do we really want to deactivate?
            if ($this->input->post('confirm') == 'yes') {
                // do we have a valid request?
                if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id')) {
                    show_error($this->lang->line('error_csrf'));
                }

                // do we have the right userlevel?
                if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin()) {
                    $this->ion_auth->deactivate($id);
                }
            }

            //redirect them back to the auth page
            redirect('admin/admin/users', 'refresh');
        }
    }

    //edit a user
    function edit_user($id) {
        $this->data['title'] = "Edit User";

        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }

        $user = $this->ion_auth->user($id)->row();
        $groups = $this->ion_auth->groups()->result_array();
        $currentGroups = $this->ion_auth->get_users_groups($id)->result();

        //validate form input
        $this->form_validation->set_rules('first_name', $this->lang->line('edit_user_validation_fname_label'), 'required|xss_clean');
        $this->form_validation->set_rules('last_name', $this->lang->line('edit_user_validation_lname_label'), 'required|xss_clean');
        $this->form_validation->set_rules('phone', $this->lang->line('edit_user_validation_phone_label'), 'required|xss_clean');
        $this->form_validation->set_rules('company', $this->lang->line('edit_user_validation_company_label'), 'required|xss_clean');
        $this->form_validation->set_rules('groups', $this->lang->line('edit_user_validation_groups_label'), 'xss_clean');

        if (isset($_POST) && !empty($_POST)) {
            // do we have a valid request?
            if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id')) {
                show_error($this->lang->line('error_csrf'));
            }

            $data = array(
                'first_name' => $this->input->post('first_name'),
                'last_name' => $this->input->post('last_name'),
                'company' => $this->input->post('company'),
                'phone' => $this->input->post('phone'),
            );

            //Update the groups user belongs to
            $groupData = $this->input->post('groups');

            if (isset($groupData) && !empty($groupData)) {

                $this->ion_auth->remove_from_group('', $id);

                foreach ($groupData as $grp) {
                    $this->ion_auth->add_to_group($grp, $id);
                }
            }

            //update the password if it was posted
            if ($this->input->post('password')) {
                $this->form_validation->set_rules('password', $this->lang->line('edit_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
                $this->form_validation->set_rules('password_confirm', $this->lang->line('edit_user_validation_password_confirm_label'), 'required');

                $data['password'] = $this->input->post('password');
            }

            if ($this->form_validation->run() === TRUE) {
                $this->ion_auth->update($user->id, $data);

                //check to see if we are creating the user
                //redirect them back to the admin page
                $this->session->set_flashdata('message', "User Saved");
                redirect("admin/admin/users", 'refresh');
            }
        }

        //display the edit user form
        $this->data['csrf'] = $this->_get_csrf_nonce();

        //set the flash data error message if there is one
        $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

        //pass the user to the view
        $this->data['user'] = $user;
        $this->data['groups'] = $groups;
        $this->data['currentGroups'] = $currentGroups;

        $this->data['first_name'] = array(
            'name' => 'first_name',
            'id' => 'first_name',
            'type' => 'text',
            'value' => $this->form_validation->set_value('first_name', $user->first_name),
        );
        $this->data['last_name'] = array(
            'name' => 'last_name',
            'id' => 'last_name',
            'type' => 'text',
            'value' => $this->form_validation->set_value('last_name', $user->last_name),
        );
        $this->data['company'] = array(
            'name' => 'company',
            'id' => 'company',
            'type' => 'text',
            'value' => $this->form_validation->set_value('company', $user->company),
        );
        $this->data['phone'] = array(
            'name' => 'phone',
            'id' => 'phone',
            'type' => 'text',
            'value' => $this->form_validation->set_value('phone', $user->phone),
        );
        $this->data['password'] = array(
            'name' => 'password',
            'id' => 'password',
            'type' => 'password'
        );
        $this->data['password_confirm'] = array(
            'name' => 'password_confirm',
            'id' => 'password_confirm',
            'type' => 'password'
        );

        $this->_render('admin/auth/edit_user', $this->data);
    }

//---------------------------------------------------------------------------------------------------------------------------------------------------------------
    public function pages() {

        $data['title'] = "Редактирование статей";
      
        
                        $this->load->library('pagination');

                        $config['base_url'] = site_url('admin/admin/pages');
                        $config['total_rows'] = $this->db->count_all('page');
                        $config['per_page'] = 1;
                        $config['uri_segment']=4;
                        $config['num_links'] = 5;    // количество ссылок в пейджере (точнее N/2)
                        $config['num_tag_open'] = '<li>';
                        $config['num_tag_close'] = '</li>';
                        $config['cur_tag_open'] = '<li class="active"><a href="#">';
                        $config['cur_tag_close'] = '</a></li>';
                        $config['first_tag_open'] = '<li>';
                        $config['first_tag_close'] = '</li>';
                        $config['last_tag_open'] = '<li>';
                        $config['last_tag_close'] = '</li>';
                        $config['next_tag_open'] = '<li>';
                        $config['next_tag_close'] = '</li>';
                        $config['prev_tag_open'] = '<li>';
                        $config['prev_tag_close'] = '</li>';
                        
                        $from=intval($this->uri->segment(4)); 
                        $this->pagination->initialize($config);

                        $data['pager'] =  $this->pagination->create_links();
        
        $data['pages'] = $this->page_model->get_pages($from);
        $this->_render('admin/pages', $data);
    }

    public function page_edit($id) {

        $this->data['title'] = "Редактирование статьи";
        //$data['pages'] = $this->page_model->get_pages();
        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }


        $this->form_validation->set_rules('titlepage', 'title', 'required');
        $this->form_validation->set_rules('link', 'link', 'required');
        $this->form_validation->set_rules('category', 'category', 'required');
        $this->form_validation->set_rules('text', 'text', 'required');

        if (isset($_POST) && !empty($_POST)) {
            if ($this->form_validation->run() == true) {

                $title = $this->input->post('titlepage');
                $link = $this->input->post('link');
                $text = $this->input->post('text');
                $category = $this->input->post('category');

                $this->page_model->update_page($id, $title, $link, $text, $category);

                redirect('admin/admin/pages', 'refresh');
            } else {

                $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
                $category = $this->page_model->get_all_category();
                $this->data['cat_id'] = $this->form_validation->set_value('category');

                $this->data['title_page'] = array(
                    'name' => 'titlepage',
                    'id' => 'titlepage',
                    'type' => 'text',
                    'value' => $this->form_validation->set_value('titlepage')
                );
                
                $this->data['category'] = $category;
                
                $this->data['link'] = array(
                    'name' => 'link',
                    'id' => 'link',
                    'type' => 'text',
                    'value' => $this->form_validation->set_value('link')
                );

                $this->data['text'] = array(
                    'name' => 'text',
                    'id' => 'text',
                    'type' => 'text',
                    'cols' => '100',
                    'style' => 'width:600px;',
                    'value' => $this->form_validation->set_value('text')
                );

                $this->load->helper('upload');
                $this->_render('admin/page_add', $this->data);
            }
        } else {
            //нет данных POST
            $result = $this->page_model->get_pages_id($id);
            
            $category = $this->page_model->get_all_category();
            // foreach ($result as $row){

            $title = $result['title'];
            $link = $result['link'];
            $text = $result['text'];
            $this->data['cat_id'] = $result['cat'];

            $this->data['title_page'] = array(
                'name' => 'titlepage',
                'id' => 'titlepage',
                'type' => 'text',
                'value' => $title
            );
            
            $this->data['category'] = $category;

            $this->data['link'] = array(
                'name' => 'link',
                'id' => 'link',
                'type' => 'text',
                'value' => $link
            );

            $this->data['text'] = array(
                'name' => 'text',
                'id' => 'text',
                'type' => 'text',
                'cols' => '100',
                'style' => 'width:600px;',
                'value' => $text
            );

            $this->load->helper('upload');
            $this->_render('admin/page_add', $this->data);


            //  }
        }
    }

    public function page_add() {

        $this->data['title'] = "Добавить статью";
        // $data['pages'] = $this->page_model->get_pages();
        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }


        $this->form_validation->set_rules('titlepage', 'title', 'required');
        $this->form_validation->set_rules('link', 'link', 'required');
        $this->form_validation->set_rules('category', 'category', 'required');
        $this->form_validation->set_rules('text', 'text', 'required');


        if ($this->form_validation->run() == true) {

            $title = $this->input->post('titlepage');
            $link = $this->input->post('link');
            $text = $this->input->post('text');
            $category = $this->input->post('category');

            $this->page_model->insert_page($title, $link, $text, $category);
            redirect('admin/admin/pages', 'refresh');
        } else {

            $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
            $category = $this->page_model->get_all_category();
            
            $this->data['cat_id'] = $this->form_validation->set_value('category');
            
            $this->data['category'] = $category;
            
            $this->data['title_page'] = array(
                'name' => 'titlepage',
                'id' => 'titlepage',
                'type' => 'text',
                'value' => $this->form_validation->set_value('titlepage')
            );

            $this->data['link'] = array(
                'name' => 'link',
                'id' => 'link',
                'type' => 'text',
                'value' => $this->form_validation->set_value('link')
            );

            $this->data['text'] = array(
                'name' => 'text',
                'id' => 'text',
                'type' => 'text',
                'cols' => '100',
                'style' => 'width:600px;',
                'value' => $this->form_validation->set_value('text')
            );

            $this->load->helper('upload');
            $this->_render('admin/page_add', $this->data);
        }
    }

    // загрузка картинок через аякс
    public function upload() {

        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }



        // $allowedExts = array("jpg", "jpeg", "gif", "png");



        $filename = $_FILES['userfile']['name'];

        $filetype = $_FILES['userfile']['type'];

        $file_content = $_FILES['userfile']['tmp_name'];

        // for file size limit, I use whichever is smallest of user defined or PHP ini file setting

        $size_limit = 2; // user set max file size in Mb..



        $size_limit = $size_limit * 1048576; // convert to bytes



        $php_size_limit = trim(ini_get('post_max_size'));

        $last = strtolower($php_size_limit[strlen($php_size_limit) - 1]);

        switch ($last) {

            case 'g':

                $php_size_limit *= 1024;

            case 'm':

                $php_size_limit *= 1024;

            case 'k':

                $php_size_limit *= 1024;
        }



        if ($php_size_limit < $size_limit) {

            $size_limit = $php_size_limit;
        }

// upload error determination..

        if (!is_uploaded_file($_FILES['userfile']['tmp_name'])) {

            $error = (!isset($_FILES['userfile']['error'])) ? 4 : $_FILES['userfile']['error'];



            switch ($error) {

                case 1:// UPLOAD_ERR_INI_SIZE

                    $cause = 'upload file size exceeds limit, ' . byte_format($php_size_limit);

                    break;

                case 2: // UPLOAD_ERR_FORM_SIZE

                    $cause = 'upload file exceeds form limit';

                    break;

                case 3: // UPLOAD_ERR_PARTIAL

                    $cause = 'partial file upload';

                    break;

                case 4: // UPLOAD_ERR_NO_FILE

                    $cause = 'no file selected';

                    break;

                case 6: // UPLOAD_ERR_NO_TMP_DIR

                    $cause = 'no temp directory for upload';

                    break;

                case 7: // UPLOAD_ERR_CANT_WRITE

                    $cause = 'upload unable to write file to disk';

                    break;

                case 8: // UPLOAD_ERR_EXTENSION

                    $cause = 'upload stopped by PHP extension';

                    break;

                default : $cause = 'no file selected';

                    break;
            }

            $response = '<p class="error">Error: ' . $cause . '</p>';
        } elseif (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $size_limit) {

            $response = '<p class="error">Error: File is too large, max allowable is ' . byte_format($size_limit) . '</p>';
        } elseif (($filetype != "image/gif") && ($filetype != "image/jpeg") && ($filetype != "image/pjpeg") && ($filetype != "image/png")) {

            $response = '<p class="error">Error: Only file types jpg, gif &amp; png are allowed;</p>';
        } else {

// if no errors call the model to add the photo for this post to my database and return the path as response

            $response = $this->page_model->add_photo($filename, $file_content);
        }

        echo $response; // echo the response back to the server
    }

    //редактируем категории
    public function cats() {

        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }

        $this->data['cats'] = $this->page_model->get_cats();
        $this->data['title'] = 'Категории';

        $this->_render('admin/cats', $this->data);
    }

    public function catedit($id) {

        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }

        $this->data['title'] = 'Редактировать категорию';
        $this->data['message'] = '';

        $this->form_validation->set_rules('link', 'link', 'required');
        $this->form_validation->set_rules('name-cat', 'name', 'required');
        
        if (isset($_POST) && !empty($_POST)) {
            if ($this->form_validation->run() == true) {

                $link = $this->input->post('link');
                $name = $this->input->post('name-cat');

                $this->page_model->edit_cat($id, $link, $name);
                redirect('admin/admin/cats', 'refresh');
            } else {

                $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');


                $this->data['link'] = array(
                    'name' => 'link',
                    'id' => 'link',
                    'type' => 'text',
                    'value' => $this->form_validation->set_value('link')
                );

                $this->data['name'] = array(
                    'name' => 'name-cat',
                    'id' => 'name-cat',
                    'type' => 'text',
                    'value' => $this->form_validation->set_value('name')
                );

                $this->_render('admin/cat_edit', $this->data);
            }
        } else {

            //нет данных POST
            $result = $this->page_model->get_cats_id($id);

            // foreach ($result as $row){


            $link = $result['link'];
            $name = $result['name'];



            $this->data['link'] = array(
                'name' => 'link',
                'id' => 'link',
                'type' => 'text',
                'value' => $link
            );

            $this->data['name'] = array(
                'name' => 'name-cat',
                'id' => 'name-cat',
                'type' => 'text',
                'value' => $name
            );

            $this->_render('admin/cat_edit', $this->data);
        }
    }
    
    public function catinsert(){
        
        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }

        $this->data['title'] = 'Редактировать категорию';
        $this->data['message'] = '';

        $this->form_validation->set_rules('link', 'link', 'required');
        $this->form_validation->set_rules('name-cat', 'name', 'required');
        
    
            if ($this->form_validation->run() == true) {

                $link = $this->input->post('link');
                $name = $this->input->post('name-cat');

                $this->page_model->insert_cat($link, $name);
                redirect('admin/admin/cats', 'refresh');
            } else {

                $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');


                $this->data['link'] = array(
                    'name' => 'link',
                    'id' => 'link',
                    'type' => 'text',
                    'value' => $this->form_validation->set_value('link')
                );

                $this->data['name'] = array(
                    'name' => 'name-cat',
                    'id' => 'name-cat',
                    'type' => 'text',
                    'value' => $this->form_validation->set_value('name')
                );

                $this->_render('admin/cat_edit', $this->data);
            }
        
        
    }
    
    public function delcat($id = NULL){
      
        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }
        
        $this->session->set_flashdata('message', $this->page_model->delcat($id));
        redirect('admin/admin/cats', 'refresh');
    }
    
    public function delpage($id=NULL){
        
        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('admin/admin/login', 'refresh');
        }
        
        $this->page_model->delpage($id);
        redirect('admin/admin/pages', 'refresh');
        
    }

}

?>
